package com.rocksea.app.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.rocksea.app.BaseFragment;
import com.rocksea.app.R;
import com.rocksea.app.activity.PhotoViewActivity;
import com.rocksea.app.db.AskQueryPileTask;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.image.ImageTable;
import com.rocksea.app.event.NotificationImage;
import com.rocksea.app.weight.OnRecyclerItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.InjectView;

/**
 * Created by 吴志华 on 2017/10/26.
 *
 * @FileName:com.rocksea.app.fragment.PhotoFragment.java
 */

public class PhotoFragment extends BaseFragment{

    public static final String PILE_EXTRA_KEY = "com.rocksea,app.PileInfoActivity.pile";
    public static final String POSITION_EXTRA_KEY = "com.rocksea,app.PileInfoActivity.pile";

    public static final String PLAN_NUM_KEY = "PLAN_NUM_KEY";
    public static final String PLIE_NO_KEY = "PLIE_NO_KEY";
    @InjectView(R.id.Pile_Images)
    RecyclerView pilePhotoList;

    private ArrayList<ImageTable> mImageTables;
    private String planNum;
    private String pileNo;

    public static PhotoFragment newInstance(Bundle bundle)
    {
        PhotoFragment fragment = new PhotoFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    protected void initView() {
        Bundle bundle = getArguments();
        if (bundle!=null)
        {
            planNum = bundle.getString(PLAN_NUM_KEY);
            pileNo = bundle.getString(PLIE_NO_KEY);
        }

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),3);
        pilePhotoList.setLayoutManager(gridLayoutManager);
        pilePhotoList.addOnItemTouchListener(new OnRecyclerItemClickListener(pilePhotoList)
        {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder)
            {
                Log.d("mRecyclerView", "onItemClick: ");
                Intent intent = new Intent(getContext(),PhotoViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList(PILE_EXTRA_KEY,mImageTables);
                intent.putExtra("111",bundle);
                intent.putExtra(POSITION_EXTRA_KEY,viewHolder.getPosition());
                startActivity(intent);
            }
            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder)
            {
                final int onLongClickPosition = viewHolder.getPosition();
                Log.d("mRecyclerView", "onLongClick: "+onLongClickPosition);
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("删除");
                builder.setMessage("确定要删除这张照片吗");
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                        String fileName = mImageTables.get(onLongClickPosition).getFileName();
                        long planId = mImageTables.get(onLongClickPosition).getPileId();
                        DbCenter.deleteImage(planId,fileName);
                        mImageTables.remove(onLongClickPosition);
                        adapter.notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(true);
                builder.show();
            }
        });
    }
    @Override
    protected void initData() {
        loading();
        AskQueryPileTask mAskQueryPileTask = new AskQueryPileTask(planNum,pileNo,mOnAskQueryCallBack);
        mAskQueryPileTask.execute();
    }
    @Override
    protected void requestAgain() {
    }
    @Override
    protected int getContentViewId() {
        return R.layout.photo_fragment_layout;
    }
    private PhotoAdapter adapter;
    private AskQueryPileTask.OnAskQueryCallBack mOnAskQueryCallBack = new AskQueryPileTask.OnAskQueryCallBack()
    {
        @Override
        public void onError()
        {
            loadFailed();
        }
        @Override
        public void onSuccess(ArrayList<ImageTable> imageTables)
        {
            if (imageTables.size()==0)
            {
                loadFailed();
                mErrorText.setText("暂无照片");
                return;
            }
            loadCompleted();
            mImageTables = imageTables;
            adapter = new PhotoAdapter(getContext(),imageTables);
            pilePhotoList.setAdapter(adapter);
        }
    };
    private static class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHodler>
    {
        private Context context;
        private ArrayList<ImageTable> pilePhotos;

        private PhotoAdapter(Context context, ArrayList<ImageTable> pilePhotos)
        {
            this.context = context;
            this.pilePhotos = pilePhotos;
        }
        @Override
        public ViewHodler onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View item = LayoutInflater.from(context).inflate(R.layout.pile_photo_list_item_layout, parent, false);
            return new ViewHodler(item);
        }
        @Override
        public void onBindViewHolder(ViewHodler holder, int position)
        {
            Glide.with(context)
                    .load(new File(pilePhotos.get(position).getFilePath()))
                    .asBitmap()
                    .into(holder.pileImage);

            if (pilePhotos.get(position).getUpLoadTime() > 0)
            {
                holder.upLoadFlag.setVisibility(View.VISIBLE);
            }
        }
        @Override
        public int getItemCount() {
            return pilePhotos.size();
        }

        public static class ViewHodler extends RecyclerView.ViewHolder {
            private ImageView pileImage;
            private ImageView upLoadFlag;
            public ViewHodler(View itemView)
            {
                super(itemView);
                pileImage = (ImageView) itemView.findViewById(R.id.ImageView);
                upLoadFlag = (ImageView) itemView.findViewById(R.id.UpLoad_Flag);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteImageNotication(NotificationImage notificationImage)
    {
        int index;
        if (notificationImage.getEventType()==NotificationImage.DELETE)
        {
            index = notificationImage.getPositon();
            mImageTables.remove(index);
            adapter.notifyDataSetChanged();
        }
        else if (notificationImage.getEventType()==NotificationImage.UPLOAD)
        {
            index = notificationImage.getPositon();
            mImageTables.get(index).setUpLoadTime(212);
            adapter.notifyDataSetChanged();
        }
    }
}
